﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace AutodeskInventorInterfaces.Model.Filters
{
  /// <summary>
  /// 处理序列化为JSON字符串时属性名称采用驼峰命名
  /// </summary>
  public class JsonResultFilter : ActionFilterAttribute
  {
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
      if (filterContext.Result is JsonResult)
      {
        filterContext.Result = new CustomJsonResult(filterContext.Result as JsonResult);
      }
    }

    private class CustomJsonResult : JsonResult
    {
      public CustomJsonResult(JsonResult jsonResult)
      {
        this.ContentEncoding = jsonResult.ContentEncoding;
        this.ContentType = jsonResult.ContentType;
        this.Data = jsonResult.Data;
        this.JsonRequestBehavior = jsonResult.JsonRequestBehavior;
        this.MaxJsonLength = jsonResult.MaxJsonLength;
        this.RecursionLimit = jsonResult.RecursionLimit;
      }

      public override void ExecuteResult(ControllerContext context)
      {
        if (context == null)
          throw new ArgumentNullException("context");

        if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet
            && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
          throw new InvalidOperationException("GET not allowed! Change JsonRequestBehavior to AllowGet.");

        var response = context.HttpContext.Response;

        response.ContentType = String.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;

        if (this.ContentEncoding != null)
          response.ContentEncoding = this.ContentEncoding;

        if (this.Data != null)
        {
          var json = JsonConvert.SerializeObject(
              this.Data,
              new JsonSerializerSettings
              {
                NullValueHandling = NullValueHandling.Ignore,
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
              });

          response.Write(json);
        }
      }
    }
  }
}